import React from "react";
import {LoadingOutlined, PlusOutlined} from '@ant-design/icons';
import {Upload} from 'antd';
import {RESOURCE_SERVICE, uploadImgType} from "../../../common/ConstField"
import Zmage from "react-zmage";
import BaseComponent from "../../../redare/components/BaseComponent";


function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
}

export default class UploadAvatar extends BaseComponent {

  static defaultProps = {
    width: "104px",
    height: "104px",
    title: '上传照片'
  };

  imgUrl = undefined;

  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      isView: false
    };
  }


  handleChange = (info) => {

    let file = info.file;

    if (file.status === 'uploading') {
      this.setState({loading: true});
      return;
    }
    if (file.status === 'done') {

      let {response} = file;
      if (response && response.code === 1) {
        this.toastFail(response.message);
      }

      this.imgUrl = response.data.url;


      // Get this url from response in real world.
      getBase64(file.originFileObj, imageUrl =>
        this.setState({
          imageUrl,
          loading: false,
        }),
      );
    }

  };

  setImgUrl(url, isView){
    this.imgUrl = url;
    this.setState({  imageUrl : url, isView: isView });
  }

  getImgUrl(){
      return this.imgUrl;
  }

  render() {

    const {imageUrl,isView} = this.state;

    const uploadButton = (
      <div>
        {this.state.loading ? <LoadingOutlined/> : <PlusOutlined/>}
        <div className="ant-upload-text">{this.props.title}</div>
      </div>
    );

    // {<div className="clearfix UploadAvatar">}

    let uploadJsx = (

      <div className="up-one-img" style={{width: this.props.width, height: this.props.height}}>
        <Upload
          name="file"
          listType="picture-card"
          showUploadList={false}
          action={`${RESOURCE_SERVICE.IMAGE}`}
          onChange={this.handleChange}
          onPreview={this.handlePreview}
          accept={uploadImgType}
        >
          <div className="one-img-show">
            {imageUrl ? <img src={imageUrl} alt="avatar" style={{width: '100%'}}/> : uploadButton}
          </div>
        </Upload>
      </div>
    );

    let viewJsx = (
      <div className={'vatar-div'} onClick={() => Zmage.browsing({src: imageUrl})}>
        <img src={imageUrl+"?scale=512x512"} alt="avatar" className={'img-show'} />
      </div>
    );

    let r_jsx = <></>;
    if( isView ){
      r_jsx = viewJsx;
    }else{
      r_jsx = uploadJsx;
    }

    return r_jsx;
  }
}